package app.controllers.customer;

import app.models.sys.AuthUsers;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.security.AppUser;
import com.github.sog.controller.security.Securitys;
import com.github.sog.kit.encry.DigestsKit;
import com.github.sog.kit.encry.EncodeKit;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

/**
 * <p>
 * .
 * </p>
 *
 * @author liuhui
 * @version 1.0 14-5-22 下午10:07
 */
public class PersonalController extends BasicController {
    public static final String FORM_ATTR = "authUsers";
    /**
     * 个人信息
     */
    public void detail() {
        AppUser loginMember = Securitys.getLoginMember();
        if (null != loginMember) {
            long id = loginMember.getId();
            AuthUsers authUsers = AuthUsers.dao.findById(id);
            setAttr(FORM_ATTR, authUsers);
            render("detail.ftl");
        }
    }

    public void updateDetail() {
        AuthUsers authUsers = getModel(AuthUsers.class);
        authUsers.update();
        redirect("/customer/index");
    }

    /**
     * 修改密码页面
     */
    public void uptPasswordPage() {
        render("uptPassword.ftl");
    }

    /**
     * 修改密码
     */
    public void updatePassword() {
        AppUser loginMember = Securitys.getLoginMember();
        if (null != loginMember) {
            long id = loginMember.getId();
            AuthUsers authUser = AuthUsers.dao.findById(id);
            String dbPassword = authUser.getStr("password");
            String oldPassword = getPara("oldPassword");

            byte[] salt = EncodeKit.decodeHex(authUser.getStr("salt"));
            byte[] hashPassword = DigestsKit.sha1(oldPassword.getBytes(), salt, EncodeKit.HASH_INTERATIONS);
            boolean equals = StringUtils.equals(EncodeKit.encodeHex(hashPassword), dbPassword);

            if (equals) {
                String newpwd = getPara("password");
                salt = DigestsKit.generateSalt(EncodeKit.SALT_SIZE);
                authUser.set("salt", EncodeKit.encodeHex(salt));
                hashPassword = DigestsKit.sha1(newpwd.getBytes(), salt, EncodeKit.HASH_INTERATIONS);
                authUser.set("password", EncodeKit.encodeHex(hashPassword));
                authUser.update();
                setAttr("msg", "恭喜你，密码修改成功");
                setAttr("states", true);
            } else {
                setAttr("msg", "原密码错误，请重新尝试");
                setAttr("states", false);
            }
            render("uptPassword.ftl");
        }
    }


    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        redirect("/admin/login");
    }
}
